<template>
  <div class="process-tracking">
    <!-- 搜索区 -->
    <el-card shadow="never" class="mb-4">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="工单编号">
          <el-input v-model="searchForm.orderNo" placeholder="输入工单编号" clearable />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.productName" placeholder="输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customer" placeholder="输入客户名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="openAddDialog">新增工单</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-table :data="filteredData" border style="width: 100%">
      <el-table-column prop="orderNo" label="工单编号" width="120"/>
      <el-table-column prop="productName" label="产品名称" width="140"/>
      <el-table-column prop="customer" label="客户" width="120"/>
      <el-table-column prop="currentStep" label="当前工序" width="120"/>
      <el-table-column label="工序进度">
        <template #default="{ row }">
          <el-steps :active="row.steps.findIndex(step => step.status === '进行中') + 1" finish-status="success" align-center>
            <el-step
              v-for="(step, idx) in row.steps"
              :key="step.name"
              :title="step.name"
              :status="step.status === '已完成' ? 'success' : (step.status === '进行中' ? 'process' : 'wait')"
              @click="editStepStatus(row, idx)"
              style="cursor:pointer"
            />
          </el-steps>
        </template>
      </el-table-column>
      <el-table-column prop="startDate" label="开工时间" width="110"/>
      <el-table-column prop="updateDate" label="更新时间" width="110"/>
      <el-table-column prop="status" label="状态" width="90">
        <template #default="{ row }">
          <el-tag :type="row.status === '正常' ? 'success' : (row.status === '异常' ? 'danger' : (row.status === '完成' ? 'info' : ''))">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row, $index }">
          <el-button size="small" @click="openEditDialog(row, $index)">编辑</el-button>
          <el-button size="small" type="danger" @click="removeOrder($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑工单弹窗 -->
    <el-dialog :title="dialogMode === 'add' ? '新增工单' : '编辑工单'" v-model="showDialog" width="500px">
      <el-form :model="dialogForm" label-width="90px" :rules="dialogRules" ref="dialogFormRef">
        <el-form-item label="工单编号" prop="orderNo">
          <el-input v-model="dialogForm.orderNo" :disabled="dialogMode === 'edit'"/>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="dialogForm.productName"/>
        </el-form-item>
        <el-form-item label="客户" prop="customer">
          <el-input v-model="dialogForm.customer"/>
        </el-form-item>
        <el-form-item label="开工时间" prop="startDate">
          <el-date-picker v-model="dialogForm.startDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:100%"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="dialogForm.status">
            <el-option label="正常" value="正常"/>
            <el-option label="异常" value="异常"/>
            <el-option label="完成" value="完成"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDialog">确定</el-button>
      </template>
    </el-dialog>

    <!-- 工序状态编辑弹窗 -->
    <el-dialog title="编辑工序状态" v-model="showStepDialog" width="400px">
      <el-form :model="stepEdit" label-width="90px">
        <el-form-item label="工序名称">
          <el-input v-model="stepEdit.stepName" disabled />
        </el-form-item>
        <el-form-item label="工序状态">
          <el-select v-model="stepEdit.stepStatus">
            <el-option label="未开始" value="未开始"/>
            <el-option label="进行中" value="进行中"/>
            <el-option label="已完成" value="已完成"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showStepDialog = false">取消</el-button>
        <el-button type="primary" @click="saveStepStatus">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const processNames = ['领料', '配料', '混合', '制粒', '干燥', '压片', '包衣', '包装']

// 模拟数据
const orders = ref(generateMockOrders())

function generateMockOrders() {
  return Array.from({ length: 15 }).map((_, i) => {
    const stepCount = Math.floor(Math.random() * processNames.length) + 1
    const steps = processNames.map((name, idx) => ({
      name,
      status: idx < stepCount - 1 ? '已完成' : (idx === stepCount - 1 ? '进行中' : '未开始')
    }))
    return {
      orderNo: `GD20250${i + 1}`,
      productName: ['头孢胶囊', '维C片', '葡萄糖注射液', '布洛芬片', '阿莫西林颗粒'][i % 5],
      customer: ['新华医药', '仁和药业', '复星医药', '哈药集团'][i % 4],
      currentStep: steps.find(step => step.status === '进行中')?.name || '已完成',
      steps,
      startDate: `2025-06-${String(i + 1).padStart(2, '0')}`,
      updateDate: `2025-06-${String(i + 3).padStart(2, '0')}`,
      status: stepCount < processNames.length ? (i % 7 === 0 ? '异常' : '正常') : '完成'
    }
  })
}

const searchForm = reactive({
  orderNo: '',
  productName: '',
  customer: ''
})

const filteredData = computed(() => {
  return orders.value.filter(item => {
    return (!searchForm.orderNo || item.orderNo.includes(searchForm.orderNo))
      && (!searchForm.productName || item.productName.includes(searchForm.productName))
      && (!searchForm.customer || item.customer.includes(searchForm.customer))
  })
})

// --- 增删改相关 ---
const showDialog = ref(false)
const dialogMode = ref('add') // add/edit
const dialogForm = reactive({
  orderNo: '',
  productName: '',
  customer: '',
  startDate: '',
  status: '正常'
})
const dialogRules = {
  orderNo: [{ required: true, message: '必填', trigger: 'blur' }],
  productName: [{ required: true, message: '必填', trigger: 'blur' }],
  customer: [{ required: true, message: '必填', trigger: 'blur' }],
  startDate: [{ required: true, message: '必填', trigger: 'blur' }]
}
const dialogFormRef = ref()
let editIndex = -1

function openAddDialog() {
  dialogMode.value = 'add'
  Object.assign(dialogForm, {
    orderNo: '',
    productName: '',
    customer: '',
    startDate: '',
    status: '正常'
  })
  showDialog.value = true
  nextTick(() => dialogFormRef.value && dialogFormRef.value.clearValidate())
}

function openEditDialog(row, index) {
  dialogMode.value = 'edit'
  Object.assign(dialogForm, {
    orderNo: row.orderNo,
    productName: row.productName,
    customer: row.customer,
    startDate: row.startDate,
    status: row.status
  })
  editIndex = index
  showDialog.value = true
  nextTick(() => dialogFormRef.value && dialogFormRef.value.clearValidate())
}

function submitDialog() {
  dialogFormRef.value.validate(valid => {
    if (!valid) return
    if (dialogMode.value === 'add') {
      // 默认全部工序未开始，第一个为进行中
      const steps = processNames.map((name, idx) => ({
        name,
        status: idx === 0 ? '进行中' : '未开始'
      }))
      orders.value.unshift({
        orderNo: dialogForm.orderNo,
        productName: dialogForm.productName,
        customer: dialogForm.customer,
        currentStep: steps[0].name,
        steps,
        startDate: dialogForm.startDate,
        updateDate: dialogForm.startDate,
        status: dialogForm.status
      })
      ElMessage.success('新增成功')
    } else {
      // 编辑
      const row = orders.value[editIndex]
      row.productName = dialogForm.productName
      row.customer = dialogForm.customer
      row.startDate = dialogForm.startDate
      row.status = dialogForm.status
      ElMessage.success('编辑成功')
    }
    showDialog.value = false
  })
}

function removeOrder(index) {
  orders.value.splice(index, 1)
  ElMessage.success('删除成功')
}

// --- 工序状态编辑 ---
const showStepDialog = ref(false)
const stepEdit = reactive({
  row: null,
  stepIdx: 0,
  stepName: '',
  stepStatus: ''
})

function editStepStatus(row, idx) {
  stepEdit.row = row
  stepEdit.stepIdx = idx
  stepEdit.stepName = row.steps[idx].name
  stepEdit.stepStatus = row.steps[idx].status
  showStepDialog.value = true
}
function saveStepStatus() {
  const { row, stepIdx, stepStatus } = stepEdit
  if (row && typeof stepIdx === 'number') {
    // 规则：只能有一个进行中，进行中前的全是已完成，后的全是未开始
    if (stepStatus === '进行中') {
      row.steps.forEach((s, idx) => {
        s.status = idx < stepIdx ? '已完成' : (idx === stepIdx ? '进行中' : '未开始')
      })
    } else if (stepStatus === '未开始') {
      row.steps.forEach((s, idx) => {
        s.status = idx < stepIdx ? '已完成' : '未开始'
      })
    } else if (stepStatus === '已完成') {
      row.steps.forEach((s, idx) => {
        s.status = idx <= stepIdx ? '已完成' : '未开始'
      })
    }
    row.currentStep = row.steps.find(s => s.status === '进行中')?.name || '已完成'
    row.status = row.currentStep === '已完成' ? '完成' : row.status
    row.updateDate = getToday()
    ElMessage.success('工序状态已更新')
  }
  showStepDialog.value = false
}

// 工具函数
function getToday() {
  const d = new Date()
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}

// --- 搜索 ---
function handleSearch() {}
function resetSearch() {
  searchForm.orderNo = ''
  searchForm.productName = ''
  searchForm.customer = ''
}
</script>

<style scoped>
.process-tracking {
  padding: 20px 16px;
}
.mb-4 {
  margin-bottom: 16px;
}
.el-step__title {
  cursor: pointer;
}
</style>
